<?php
/**
 * @package LaravelBoot
 *
 * @internal
 *
 * @author mawenpei
 * @date 2019/3/18 14:50
 * @version
 */
namespace Modules\Service\Logic;

use App\Models\Draw;
use App\Models\MobileRechargeOrder;
use App\Models\MobileRechargeOrderDetail;
use App\Models\MobileRechargeTask;
use App\Models\OilCard;
use App\Models\Pay;
use App\Models\RechargeOrder;
use App\Models\RechargeTask;
use App\Models\ShopOrder;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Str;
use App\Models\Configure;

class PayLogic extends BaseLogic
{
    public static function doPaySuccess($out_trade_no)
    {
        $pay = Pay::query()->where('pay_sn',$out_trade_no)->first();
        if(!$pay){
            Log::error('out_trade_no:' . $out_trade_no . ' pay record is not exists');
            return false;
        }
        if($pay->is_paid){

            return true;
        }

        if(self::isYouKaOrder($out_trade_no)){
            return self::doYouka($out_trade_no);
        }

        if(self::isHuaFeiOrder($out_trade_no)){
            return self::doHuafei($out_trade_no);
        }

        if(self::isShopOrder($out_trade_no)){
            return self::doShop($out_trade_no);
        }
    }

    public static function doYouka($out_trade_no)
    {
        DB::beginTransaction();
        try{
            $pay = Pay::query()->where('pay_sn',$out_trade_no)->first();
            $user_id = $pay->user_id;
            $pay_id = $pay->id;
            //更新支付状态
            $next = Pay::query()->where('pay_sn',$out_trade_no)->where('is_paid',0)->update(['is_paid'=>1,'paid_at'=>Carbon::now()->toDateTimeString()]);
            if($next) {
                //首冲送88元优惠券
                $count = RechargeOrder::query()->where('user_id', $user_id)->where('status', '>', 0)->where('status', '<', 7)->count();
                if ($count == 0) {
                    $regCouponIds = Configure::rechargeCoupon();
                    if ($regCouponIds) {
                        foreach ($regCouponIds as $couponId) {
                            UserCoupon::sendToUser($couponId, $user_id);
                        }
                    }
                }
                //更新订单状态
                $order = RechargeOrder::query()->where('user_id', $user_id)->where('pay_id', $pay_id)->first();
                if ($order) {
                    RechargeOrder::query()->where('id', $order->id)->update(['status' => RechargeOrder::STATUS_PAID, 'paid_at' => Carbon::now()->toDateTimeString()]);
                    //更新优惠券使用状态
                    if ($order->coupon_id) {
                        UserCoupon::query()->where('id', $order->coupon_id)->update(['status' => 2]);
                    }
                    $card = OilCard::query()->where('id', $order->oil_card_id)->where('user_id', $user_id)->first();
                    if (!$card) {
                        Log::error('pay error:' . $out_trade_no . ' order card is not exists');
                        return false;
                    }
                    //套餐生成充值明细
                    $recharge_amount = 0;
                    $pending_amount = 0;
                    if ($order->type == RechargeOrder::TYPE_RECHARGE) {
                        //
                        for ($i = 1; $i < $order->months; $i++) {
                            //首月套餐次月到账
                            if ($order->months == 1 && $i == 1) {
                                $payAt = Carbon::parse('+1 months')->toDateTimeString();// 一个月套餐充值
                            } else {
                                $payAt = Carbon::now()->addMonths($i - 1)->toDateTimeString();// N个月套餐充值
                            }

                            $detail = RechargeOrderDetail::create([
                                'recharge_order_id' => $order->id,
                                'current_month' => $i,
                                'total_month' => $order->months,
                                'user_id' => $user_id,
                                'oil_card_id' => $card->id,
                                'card_no' => $card->card_no,
                                'card_type' => $card->type,
                                'card_mobile' => $card->mobile,
                                'amount' => $order->recharge_amount,
                                'pay_at' => $payAt,
                            ]);

                            // 创建充值任务
                            RechargeTask::createTask($card, $detail->amount, $payAt, $order->id, $detail->id);
                        }
                        //
                        $recharge_amount = $pending_amount = $order->recharge_amount * $order->months;
                    } else {//直充创建任务
                        //
                        $payAt = Carbon::now()->toDateTimeString();
                        RechargeTask::createTask($card, $order->recharge_amount, $payAt, $order->id);
                        //
                        $recharge_amount = $order->recharge_amount;
                        $pending_amount = $order->recharge_amount;
                    }
                    //更新用户累计充值总额
                    User::query()->where('id', $user_id)->increment('recharge_amount', $recharge_amount);
                    User::query()->where('id', $user_id)->increment('pending_amount', $pending_amount);
                    //赠送抽奖次数
                    $times = floor($recharge_amount /100);
                    if($times > 0){
                        $draw = Draw::query()->where('user_id',$user_id)->first();
                        if($draw){
                            Draw::query()->where('user_id',$user_id)->increment('num',$times);
                        }else{
                            Draw::create([
                                'user_id'=>$user_id,
                                'num'=>$times
                            ]);
                        }
                    }
                }
            }

            DB::commit();
            return true;
        }catch(\Exception $e){
            Log::error('pay error:' . $e->getMessage());
            DB::rollBack();
        }
        return false;
    }

    public static function doHuafei($out_trade_no)
    {
        DB::beginTransaction();
        try {
            $pay = Pay::query()->where('pay_sn', $out_trade_no)->first();
            $user_id = $pay->user_id;
            $pay_id = $pay->id;
            //更新支付状态
            $next = Pay::query()->where('pay_sn', $out_trade_no)->where('is_paid', 0)->update(['is_paid' => 1, 'paid_at' => Carbon::now()->toDateTimeString()]);
            if ($next) {
                //更新订单状态
                $order = MobileRechargeOrder::query()->where('user_id', $user_id)->where('pay_id', $pay_id)->first();
                if($order){
                    MobileRechargeOrder::query()->where('id', $order->id)->update(['status' => RechargeOrder::STATUS_PAID, 'paid_at' => Carbon::now()->toDateTimeString()]);
                    //更新优惠券使用状态
                    if ($order->coupon_id) {
                        UserCoupon::query()->where('id', $order->coupon_id)->where('user_id',$user_id)->update(['status' => 2]);
                    }

                    // 生成充值明细
                    if ($order->type == MobileRechargeOrder::TYPE_RECHARGE) {
                        for ($i = 1; $i <= $order->months; $i++) {
                            if ($order->months==1 && $i == 1) {
                                $payAt = Carbon::parse('+1 months')->toDateTimeString();// 一个月套餐充值
                            } else {
                                $payAt = Carbon::now()->addMonths($i-1)->toDateTimeString();// N个月套餐充值
                            }


                            $detail = MobileRechargeOrderDetail::create([
                                'recharge_order_id' => $order->id,
                                'current_month'     => $i,
                                'total_month'       => $order->months,
                                'user_id'           => $user_id,
                                'amount'            => $order->recharge_amount,
                                'mobile'            => $order->mobile
                            ]);
                            // 创建充值任务
                            MobileRechargeTask::createTask($order->mobile,$detail->amount,$payAt, $order->id, $detail->id);
                        }
                    }else{
                        $payAt = Carbon::now()->toDateTimeString();
                        MobileRechargeTask::createTask($order->mobile,$order->recharge_amount,$payAt, $order->id,0);
                    }
                }
            }
            DB::commit();
            return true;
        }catch(\Exception $e){
            Log::error('pay error:' . $e->getMessage());
            DB::rollBack();
        }
        return false;
    }

    public static function doShop($out_trade_no)
    {
        DB::beginTransaction();
        try {
            $pay = Pay::query()->where('pay_sn', $out_trade_no)->first();
            $user_id = $pay->user_id;
            $pay_id = $pay->id;
            //更新支付状态
            $next = Pay::query()->where('pay_sn', $out_trade_no)->where('is_paid', 0)->update(['is_paid' => 1, 'paid_at' => Carbon::now()->toDateTimeString()]);
            if ($next) {
                //更新订单状态
                $order = ShopOrder::query()->where('user_id', $user_id)->where('pay_id', $pay_id)->first();
                if($order){
                    ShopOrder::query()->where('id', $order->id)->update(['status' => 1, 'pay_time' => Carbon::now()->toDateTimeString()]);
                    //更新优惠券使用状态
                    if ($order->coupon_id) {
                        UserCoupon::query()->where('id', $order->coupon_id)->where('user_id',$user_id)->update(['status' => 2]);
                    }
                }
            }
            DB::commit();
            return true;
        }catch(\Exception $e){
            Log::error('pay error:' . $e->getMessage());
            DB::rollBack();
        }
        return false;
    }

    /**
     *
     * @param $pay_sn
     * @return bool
     */
    public static function isYouKaOrder($pay_sn)
    {
        return strpos($pay_sn,'YK') === 0 ? true : false;
    }

    /**
     *
     * @param $pay_sn
     * @return bool
     */
    public static function isHuaFeiOrder($pay_sn)
    {
        return strpos($pay_sn,'HF') === 0 ? true : false;
    }

    public static function isShopOrder($pay_sn)
    {
        return strpos($pay_sn,'SH') === 0 ? true : false;
    }
}